# encoding=utf8
import json
import numpy as np
import base64
import cv2
from glob import glob
from tqdm import tqdm
import re
import os
import json

'''
功能：根据craft生成的字符坐标转换成labelme标注的json
'''


def img2base64(img_path):
    with open(img_path, 'rb') as fin:
        image_data = fin.read()
        print(image_data)
        base64_data = base64.b64encode(image_data)
    return base64_data.decode()


def label_point(polys):
    li = []
    for point in polys:
        label = {}
        label['label'] = 'fkjajk'
        label['points'] = point.tolist()
        label['group_id'] = None
        label['shape_type'] = 'polygon'
        label['flags'] = {}
        li.append(label)
    return li


def txt2json(image_path, img_name, polys):
    img = cv2.imread(image_path)
    root = {}
    root['version'] = '4.2.10'
    root['flags'] = {}
    root['shapes'] = label_point(polys)
    root['imagePath'] = img_name

    root['imageData'] = img2base64(image_path)
    root['imageHeight'] = img.shape[0]  # 5248
    root['imageWidth'] = img.shape[1]  # 2113
    return root
    # dd = json.dumps(dd,indent=4)


'''
功能：根据labelme生成的json,转换成synth80k一样的数据样本
'''


def take(elem):
    return elem[:]['label']


def json2trainDataSynth(path):
    # path = "result/hcp1/01249234-20200228-0010037804_005-0.json"
    with open(path) as json_file:
        result = json.load(json_file)
        shape = result['shapes']
        shape = sorted(shape, key=lambda e: e['label'], reverse=True)
        point_list = []
        label_list = []
        for sh in shape:
            point = np.array(sh['points'])
            point_list.append(point)
            label_list.append(sh['label'])
        point_list = np.array(point_list)
    return point_list, label_list


# path = 'C:/Users/Administrator/PycharmProjects/craft/myself_craft/ocr_server/result/hcp_finsh/json/01249234-20200228-0010037804_005-0.json'
def json2trainData2015(path):
    # path = "result/hcp1/01249234-20200228-0010037804_005-0.json"
    # result = json.loads(path)
    with open(path) as json_file:
        result = json.load(json_file)
        shape = result['shapes']
        shape = sorted(shape, key=lambda e: e['label'], reverse=True)
        point_list = []
        label_list = []
        for sh in shape:
            point = np.array(sh['points'])
            point_list.append(point)
            label_list.append(sh['label'])
        point_list = np.array(point_list)
    total = 0
    words = sorted(set(label_list), key=label_list.index)
    # img  = cv2.imread('C:/Users/Administrator/PycharmProjects/craft/myself_craft/ocr_server/result/hcp_finsh/img\\01249234-20200228-0010037804_005-0.jpg')
    Weak_label_list = []
    for i in range(len(words)):
        bboxes = point_list[total:total + len(words[i])]  # 拿到第一个字符串的每个字符的坐标，如“lines：”，则维度为[6,4,2]
        assert (len(bboxes) == len(words[i]))
        total += len(words[i])
        xmin, ymin, xmax, ymax = int(bboxes[:, :, 0].min()), int(bboxes[:, :, 1].min()), int(
            bboxes[:, :, 0].max()), int(bboxes[:, :, 1].max())
        coor = str(xmin) + ',' + str(ymin) + ',' + str(xmax) + ',' + str(ymin) + ',' + str(xmax) + ',' + str(
            ymax) + ',' + str(xmin) + ',' + str(ymax) + ',' + str(words[i])
        Weak_label_list.append(coor)
        # cv2.rectangle(img,(int(xmin),int(ymin)),(int(xmax),int(ymax)),(0,0,255),1)
        # cv2.imshow('img',img)
        # cv2.waitKey(0)
    return Weak_label_list


from itertools import chain


def json2txt(path):
    file, ext = os.path.splitext(path)
    txtpath = file + '.txt'
    with open(txtpath, 'w+', encoding='utf-8') as f:
        # (path, filename) = os.path.split(path)
        with open(path) as json_file:
            result = json.load(json_file)
            shape = result['shapes']
            shape = sorted(shape, key=lambda e: e['label'], reverse=True)
            point_list = []
            label_list = []
            for sh in shape:
                point = np.array(sh['points'])
                pointstr = list(chain.from_iterable(point))
                pointstr = str(pointstr).replace('[', '').replace(']', '') + ',' + sh['label'].replace('：',':') + '\n'
                f.write(pointstr)
            #     point_list.append(point)
            #     label_list.append(sh['label'])
            # point_list = np.array(point_list)
    f.close()


def txt2trainDataSynth(path):
    point_list = []
    label_list = []
    with open(path, 'r', encoding='utf-8') as f:
        lines = f.read().split('\n')
        for line in lines:
            data_split = line.split(',')
            if len(data_split) == 9:
                point = np.array(list(map(float, data_split[:-1]))).reshape(4, 2)
                point_list.append(point)
                label_list.append(data_split[-1])
            else:
                pass
    point_list = np.array(point_list)
    return point_list, label_list


def txt2trainData2015(path):
    point_list = []
    label_list = []
    with open(path, 'r', encoding='utf-8') as f:
        lines = f.read().split('\n')
        for line in lines:
            data_split = line.split(',')
            if len(data_split) == 9:
                point = np.array(list(map(float, data_split[:-1]))).reshape(4, 2)
                point_list.append(point)
                label_list.append(data_split[-1])
            else:
                pass
    point_list = np.array(point_list)
    total = 0
    words = sorted(set(label_list), key=label_list.index)
    # img  = cv2.imread('C:/Users/Administrator/PycharmProjects/craft/myself_craft/ocr_server/result/hcp_finsh/img\\01249234-20200228-0010037804_005-0.jpg')
    Weak_label_list = []
    for i in range(len(words)):
        bboxes = point_list[total:total + len(words[i])]  # 拿到第一个字符串的每个字符的坐标，如“lines：”，则维度为[6,4,2]
        assert (len(bboxes) == len(words[i]))
        total += len(words[i])
        xmin, ymin, xmax, ymax = int(bboxes[:, :, 0].min()), int(bboxes[:, :, 1].min()), int( bboxes[:, :, 0].max()), int(bboxes[:, :, 1].max())
        coor = str(xmin) + ',' + str(ymin) + ',' + str(xmax) + ',' + str(ymin) + ',' + str(xmax) + ',' + str( ymax) + ',' + str(xmin) + ',' + str(ymax) + ',' + str(words[i])
        Weak_label_list.append(coor)
        # cv2.rectangle(img,(int(xmin),int(ymin)),(int(xmax),int(ymax)),(0,0,255),1)
        # cv2.imshow('img',img)
        # cv2.waitKey(0)
    return Weak_label_list
# path = 'C:/Users/Administrator/PycharmProjects/craft/myself_craft/ocr_server/result/hcp_finsh/json/01249234-20200228-0010037804_005-0.txt'
# txt2trainData2015(path)

# if __name__ == '__main__':
#     fd = 'C:/Users/Administrator/PycharmProjects/craft/myself_craft/ocr_server/result/hcp_finsh/json'
#     imgs = glob(fd + '/*.json')
#     for img in tqdm(imgs):
#         json2txt(img)


# if __name__ == '__main__':
#     fd = 'C:/Users/Administrator/PycharmProjects/craft/myself_craft/ocr_server/result/hcp_finsh/txt'
#     imgs = glob(fd + '/*.txt')
#     for img in tqdm(imgs):
#     #     print(img)
#     # img = 'C:/Users/Administrator/PycharmProjects/craft/myself_craft/ocr_server/result/hcp_finsh/txt/01368170-200228-0010010610_004-0.txt'
#         Weak_label_list,_ = txt2trainDataSynth(img)



